package main

import (
	"context"
	"fmt"
	"io"
	"time"

	"gitlab.com/go-course-project/go17/skills/grpc/service"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
)

func main() {
	// Deprecated: use WithTransportCredentials and insecure.NewCredentials()
	// instead. Will be supported throughout 1.x.
	conn, err := grpc.NewClient("localhost:1234", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		panic(err)
	}

	client := service.NewHelloServiceClient(conn)
	// resp, err := client.Hello(context.Background(), &service.HelloRequest{
	// 	MyName: "bob",
	// })
	// if err != nil {
	// 	panic(err)
	// }
	// fmt.Println(resp)

	stream, err := client.Chat(context.Background())
	if err != nil {
		panic(err)
	}

	// 1. 处理返回结果的在后台
	go func() {
		for {
			resp, err := stream.Recv()
			if err != nil {
				// 如果遇到io.EOF表示客户端流被关闭
				if err == io.EOF {
					break
				}
				fmt.Println(err)
				return
			}
			fmt.Println(resp)
		}
	}()

	// 2. 发送请求的在主Goroutine
	for i := range 10 {
		stream.Send(&service.ChatRequest{
			Id:      uint64(i + 1),
			Message: "test",
		})
		time.Sleep(1 * time.Second)
	}
}
